package xilin

import org.codehaus.groovy.grails.commons.DefaultGrailsDomainClass

class XilinTagLib {
    static namespace = 'x'

    /*
     * Usage: <x:setupTablesorter controllerName="${controllerName}" canUpdate=${session.roles?.contains('ROLE_ADMIN')}/>
    */
    def setupTablesorter = {attrs ->
        def tableId = "#" + attrs.controllerName + "Table";
        def outStr = '''
            <script type="text/javascript">
              $(function(){
                  $(${tableId}).tablesorter( {
                    headers: {
                      0: { sorter: false },
                      1: { sorter: false }
                    }
                  });

                  if (attrs.canUpdate) {
                    $('.delete, .edit').show();
                  }

                  $(${tableId} + " .edit > a").cluetip({activation:'click', sticky:true, closePosition:'title'});
                  $(${tableId} + " .show > a").cluetip({activation:'click', sticky:true, closePosition:'title'});
              });
            </script>
        '''
        out << outStr
    }

    def component = {attrs ->
        out << """
            <div class="block">
                <div class="block-body">
                    <div class="blockheader">
                        <div class="l"></div>
                        <div class="r"></div>
                        <div class="t">${attrs.title}</div>
                    </div>
                    <div class="blockcontent">
                        <div class="blockcontent-cc"></div>
                        <div class="blockcontent-body">
                """
        out << render(template:"${attrs.template}")
        out << """
                            <div class="cleared"></div>
                        </div>
                    </div>
                    <div class="cleared"></div>
                </div>
            </div>
            """
    }


    /*
     * Usage: <x:pager/>
    */
    def pager = {
        def outStr = '''
            <div id="pager" class="pager right" style="display:inline;">
              <form>
                <img src="images/pager/first.png" class="first" style="margin-top:0"/>
                <img src="images/pager/prev.png" class="prev"/>
                <input type="text" class="pagedisplay"/>
                <img src="images/pager/next.png" class="next"/>
                <img src="images/pager/last.png" class="last"/>
                <select class="pagesize pagerSelect">
                  <option value="5">5</option>
                  <option selected="selected" value="10">10</option>
                  <option value="15">15</option>
                  <option value="20">20</option>
                </select>
              </form>
            </div>
        '''
        out << outStr
    }

    /*
     * Usage: <x:message message=''/>
    */
    def message = { attr ->
        if (attr.message && attr.message.size() > 0) {
            out << """
                <DIV style="PADDING-BOTTOM: 0px; MARGIN-TOP: 0px; PADDING: 0.7em" class="ui-state-highlight ui-corner-all">
                <P><SPAN style="FLOAT: left; MARGIN-RIGHT: 0.3em" class="ui-icon ui-icon-info"></SPAN><span class="message">${attr.message}</span></P>
                </DIV>
            """
        }
    }

    /*
     * Usage: <x:vmenu links="[[link:'semester', text:'Semester']]" />
    */
    def vmenu = { attr ->
        def outStr = """<ul class="vmenu">"""

        attr.links.each {
            outStr += '<li class="active">'
            outStr += """<a class="active" href="javascript:void(0)" onclick="\$('.content').load('${request.contextPath}/${it.link}')">${it.text}</a>"""
            outStr += '</li>'
        }
        outStr <<  """</ul>"""
        out << outStr
    }

    /*
     * Usage: <x:semesterSelection/>
    */
    def semesterService
    def classRegisterService

    def semesterSelection = { attr ->

        def activeSemesters = semesterService.getActiveSemesters()
        out << """<select name="activeSemesterSel" onChange="changeActiveSemester(this.options[this.selectedIndex].value)">"""
        activeSemesters.each {
            if (attr?.semesterId == it.id) {
                out << """
                  <option value="${it.id}" selected>${it}</option>
                """
            }
            else {
                out << """
                  <option value="${it.id}">${it}</option>
                """
            }
        }
        out << """</select>"""
    }

    def search = { attr ->

        def domainClass = new DefaultGrailsDomainClass( attr.domainClass )


        out << """<select class="findByProperty">"""
        domainClass.properties.each{

            def type = it.type.toString().split(' ')[1]
            if (type.startsWith('java.lang')) {
                out << """
                  <option value="${it.name + "," + type}">${it.name}</option>
                """
            }        
        }
        out << """</select>"""
        out << """ = <input class="findByValue" value=""/><input type="button" value="search" onclick="findBy(\$('.findByProperty').val(), \$('.findByValue').val(), '${domainClass.getFullName()}', '${domainClass.getName()}')"/>"""
    }

    def studentSelection = { attr ->
        def students = classRegisterService.getMyStudents()
        out << """<select name="studentId" onChange="changeStudent(this.options[this.selectedIndex].value)">"""

        students.each { it->
            if (attr?.studentId == (it.id as String)) {
                 out << """
                  <option value="${it.id}" selected>${it}</option>
                """
            }
            else {
                out << """
                  <option value="${it.id}">${it}</option>
                """
            }
        }
        out << """</select>"""
    }
}
